/*************************************************************************
	> File Name: 007.printf简版实现.c
	> Author: Maureen 
	> Mail: Maureen@qq.com 
	> Created Time: 一  8/23 09:16:26 2021
 ************************************************************************/

#include <stdio.h>
#include <stdarg.h>

int my_printf(const char *frm, ...) {
    va_list arg;
    va_start(arg, frm);
    int cnt = 0;
    #define PUTC(a) putchar(a), ++cnt
    for (int i = 0; frm[i]; i++) {
        switch (frm[i]) {
            //打印变量值需要判断格式控制字符串，需要判断%的情况
            case '%' : {
                switch (frm[++i]) {
                    case '%': {
                        PUTC(frm[i]);
                    } break;
                    case 'd': {
                        //do-while是为了打印变量值为0的情况
                        //digit变量是因为当变量值为1000时，并不正确，所以要记录位数
                        int x = va_arg(arg, int), temp = 0, digit = 0;
                        if (x < 0) x = -x, PUTC('-'); //负数情况
                        do { //先翻转字符串
                            temp = temp * 10 + x % 10;
                            x /= 10;
                            digit += 1;
                        } while (x);
                        while (digit--) { //再打印字符串
                            PUTC(temp % 10 + 48); //+48:转换为字符
                            temp /= 10;
                        }
                    } break;
                } 
            } break;
            default: PUTC(frm[i]); break;
        }
    }
    #undef PUTC
    va_end(arg);
    return cnt;
}

int main() {
    int a =  123;
    //1. 打印字符串
    printf("Hello world!\n");
    my_printf("Hello world!\n");
    //2. 打印变量值 
    printf("int a = %d\n", a);
    my_printf("int a = %d\n", a);

    printf("int a = %d\n", 1000);
    my_printf("int a = %d\n", 1000);

    printf("int a = %d\n", 0);
    my_printf("int a = %d\n", 0);

    printf("int a = %d\n", -234);
    my_printf("int a = %d\n", -234);
    return 0;
}
